<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class IQCmd extends Command
{
    /**
     * 唯一控制台命令名称
     *
     * @var string
     */
    protected $signature = 'iq:cmd {cmd}';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = 'IQStructs 便捷命令';

    /**
     * 创建命令构造方法
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 命令执行的实体
     *
     * @return mixed
     */
    public function handle()
    {
        //首先获取项目根目录
        $basedir = str_replace("\\", "/", base_path());

        if ($this->argument('cmd') == 'bom') {                 //自动处理 BOM头文件
            $this->clearDirBom($basedir);

        } elseif ($this->argument('cmd') == 'gitkeep-add') {  //自动Git空目录生成.gitkeep文件
            $this->gitkeepAdd($basedir);

        } elseif ($this->argument('cmd') == 'gitkeep-del') {  //自动Git空目录删除.getkeep文件
            $this->gitkeepDel($basedir);
        }
    }

    /**
     * 递归检测目录
     */
    private function clearDirBom($basedir)
    {
        $dh = opendir($basedir);
        while (($file = readdir($dh)) !== false) {      //读取目录
            if ($file == "." || $file == "..") continue;

            if (is_dir("$basedir/$file")) {
                $this->clearDirBom("$basedir/$file");  //递归遍历目录
            } else {
                if ($this->checkBOM("$basedir/$file")) {
                    echo "FileName: $basedir/$file  BOM head, Automatically processing.\n";
                }
            }
        }
        closedir($dh);
    }

    /**
     * 检查文件是否存在BOM头
     */
    private function checkBOM($filename)
    {
        $contents = file_get_contents($filename);
        //取出文件里前三个字符
        $charset[1] = substr($contents, 0, 1);
        $charset[2] = substr($contents, 1, 1);
        $charset[3] = substr($contents, 2, 1);
        //转换成ASCII码值与BOM头进行比对
        if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
            $rest = substr($contents, 3);
            $this->rewrite($filename, $rest);
            return true;
        }
    }

    /**
     * 重写文件（去BOM头）
     */
    private function rewrite($filename, $data)
    {
        $filenum = fopen($filename, "w");
        flock($filenum, LOCK_EX);
        fwrite($filenum, $data);
        fclose($filenum);
    }


    /**
     * 遍历空目录，添加.gitkeep文件
     */
    private function gitkeepAdd($basedir)
    {
        $handle = opendir($basedir);
        while (($file = readdir($handle)) !== false) {
            if ($file == "." || $file == "..") continue;
            if (is_dir("$basedir/$file")) {
                if (count(scandir("$basedir/$file")) == 2) {    //目录为空,=2是因为.和..存在
                    $temp = fopen("$basedir/$file/.gitkeep", "wb");   //创建.gitkeep文件
                    fclose($temp);
                    echo "$basedir/$file/.gitkeep add OK. \n";
                } else {    // 如果是目录则递归遍历
                    $this->gitkeepAdd("$basedir/$file");
                }
            }
        }
        closedir($handle);
    }

    /**
     * 遍历目录删除.gitkeep文件
     */
    public function gitkeepDel($basedir)
    {
        $handle = opendir($basedir);
        while (($file = readdir($handle)) !== false) {
            if ($file == "." || $file == "..") continue;
            if (is_dir("$basedir/$file")) {
                //目录下只有.gitignore文件,=3是因为.和..存在
                if (count(scandir("$basedir/$file")) == 3 && in_array('.gitkeep', scandir("$basedir/$file"))) {
                    unlink("$basedir/$file/.gitkeep");   //删除.gitkeep文件
                    echo "$basedir/$file/.gitkeep remove OK. \n";
                } else {    // 如果是目录则递归遍历
                    $this->gitkeepDel("$basedir/$file");
                }
            }
        }
        closedir($handle);
    }
}
